$import("com.joypard.platform.security.role.RoleGridCompoent");
$import("com.joypard.platform.security.role.roleresources.RoleResourcesDI");
$import("com.joypard.platform.security.resource.ResourceDI");

/**
 * 角色分配用户管理-视图层
 */
K.defView("com.joypard.platform.security.role.roleresources.RoleResourcesView", {

	roleId : null, // 保存角色ID
	roleRs : null, // 保存角色的原有资源
	addRoleRs : null, // 将要新增关联的资源
	delRoleRs : null, // 将要删除关联的资源

	purviewConfig : {
		assingResources : "platform.security.role.roleResource.assingResources"
	},

	// 初始化
	initialize : function() {
		E.addListener("getRsByRoleIdSuccessEvent", this.onGetRsByRoleIdSuccessEvent, this);
		E.addListener("assignResourcesSuccessEvent", this.onAssignResourcesSuccessEvent, this);
	},
	// 渲染后初始化视图
	render : function() {
		this.roleGridPanel = this.createRoleGridPanel();// 搜索角色面板
		this.rsTreePanel = this.createResourceTree();// 资源树面板
		this.resViewPanel = this.createResourceViewPanel();// 角色信息面板

		this.MP = new K.Ext.MainPanel({
			items : [ this.roleGridPanel, this.rsTreePanel, this.resViewPanel ]
		});
	},

	/**
	 * 左边角色搜索面板
	 */
	createRoleGridPanel : function() {
		var me = this;
		var roleGridPanel = RoleGridCompoent.createCompoentPanel({
			margins : '2 0 2 2',
			split : true,
		});
		RoleGridCompoent.roleGridPanel.getSelectionModel().on("rowselect", function(selModel, rowIndex, r) {
			me.roleId = r.id;
			E.fireEvent("getRsByRoleIdEvent", {
				id : r.id
			});
		});
		RoleGridCompoent.roleGridPanel.getStore().on("load", function(store,records,options) {
			if (records.length > 0 ) {
				RoleGridCompoent.roleGridPanel.getSelectionModel().selectRow(0);
				me.setButtonEnable("show");
			}else{
				me.setButtonEnable("hidden");
				me.rsTreePanel.setRootNode({
					id : '0',
					text:'没有任何数据',
					hidden : true
				});
			}
		});
		return roleGridPanel;
	},

	/**
	 * 获取资源树加载器
	 */
	createResourcesTreeLoader : function() {
		var me = this;
		var loader = new K.Ext.tree.TreeLoader({
			url : RoleResourcesDI.urls.URL_getChildrens,
			listeners : {
				beforeload : function(loader, node) {
					this.baseParams.parentResId = node.id;
				}
			},
			createNode : function(attr) {
				attr.checked = false;
				if (me.roleRs) {
					$.each(me.roleRs, function(i, v) {
						if (attr.id == v) {
							attr.isRelated = true;
							attr.checked = true;
							return false;
						}
					});
				}
				attr.text = attr.name;
				return K.Ext.tree.TreeLoader.prototype.createNode.call(this, attr);
			}
		});
		return loader;
	},

	/**
	 * 读取资源树的根信息
	 */
	createResourceRootNode : function(resId) {
		var rootNode = null;
		$.ajax({
			url : RoleResourcesDI.urls.URL_getResById,
			data : {
				resId : resId
			},
			async : false,
			success : function(json) {
				rootNode = K.output(json).getParameter("resource");
				//rootNode.iconCls = "res_icon_Root";
				rootNode.isRoot = true;
				rootNode.text = rootNode.name;
				rootNode.leaf = rootNode.leaf == 1;
			}
		});
		return rootNode;
	},

	/**
	 * 创建资源树
	 */
	createResourceTree : function() {
		var me = this;
		var options = {
			title : "资源树",
			iconCls : "p-panel",
			autoScroll : true,
			region : "center",
			margins : '2 0 2 0',
			width : '30%',
			split : true,
			valueField : "id",
			tbar : [ {
				id:'saveInfoBtn',
				text : '保存',
				iconCls : "save",
				hidden : !RoleResourcesView.purviewAssingResources(),
				handler : function() {
					var roleId = me.roleId;
					if (roleId) {
						if (me.addRoleRs.length == 0 && me.delRoleRs.length == 0) {
							K.err("你未做任何更改", me.rsTreePanel.tbar);
							return;
						} else {

							var addRs = [];
							var delRs = [];

							$.each(me.addRoleRs, function(i, v) {
								addRs.push(v.id);
							});

							$.each(me.delRoleRs, function(i, v) {
								delRs.push(v.id);
							});

							E.fireEvent("assignResourcesEvent", {
								roleId : roleId,
								addRs : addRs.join(","),
								delRs : delRs.join(",")
							});
						}
					} else {
						K.err("请选择左边列表的角色", me.rsTreePanel.tbar);
					}
				}
			}, '->', {
				text : "展开",
				id:'expandTreeBtn',
				iconCls : "add",
				handler : function() {
					me.rsTreePanel.getRootNode().expand(true);
				}
			} ],
			listeners : {
				checkchange : function(node, checked) {
					var parentNode = node.parentNode;
					if (parentNode !== null) {
						me.parentCheck(parentNode, checked);
					}
					node.attributes.checked = checked;

					me.setAddOrDelRs(node, checked);

					node.eachChild(function(child) {
						child.ui.toggleCheck(checked);
						child.attributes.checked = checked;
					});
				},
				expandnode : function(node) {
					if (me.halfchoose(node) && node.attributes.checked && !(node.getUI().checkbox.indeterminate)) {
						node.getUI().checkbox.indeterminate = true;
					}
				}
			}
		};
		// K.extend(options, config);
		options.loader = this.createResourcesTreeLoader();
		var rsTreePanel = new K.Ext.tree.TreePanel(options);

		rsTreePanel.getSelectionModel().on("selectionchange", function(sm, node) {
			me.resViewPanel.load({
				url : ResourceDI.urls.resView,
				params : {
					resId : node.id
				}
			});
		});

		return rsTreePanel;
	},

	/**
	 * 资源树向上级联
	 */
	parentCheck : function(node, checked) {
		var me = this;
		var checkbox = node.getUI().checkbox;
		if (typeof checkbox == 'undefined') {
			return false;
		}

		// 取消节点时 ，父节点还有其他的子节点时，将父节点设置有半选
		if (!checked && me.childHasChecked(node)) {
			node.getUI().checkbox.indeterminate = true;
			return false;
		} else if (!checked && !me.childHasChecked(node)) {
			node.getUI().checkbox.indeterminate = false;
		}

		// 勾选节点时 ，父节点半选状态时，设置半选状态
		if (checked && me.halfchoose(node)) {
			if (node.attributes.checked === true) {
				return false;
			}
			node.getUI().checkbox.indeterminate = true;

		} else if (checked && !me.halfchoose(node)) {
			node.getUI().checkbox.indeterminate = false;
			return false;
		}

		checkbox.checked = checked;
		node.attributes.checked = checked;
		me.setAddOrDelRs(node, checked)

		var parentNode = node.parentNode;
		if (parentNode !== null) {
			this.parentCheck(parentNode, checked);
		}
	},

	/**
	 * 是否有子项
	 */
	childHasChecked : function(node) {
		var childNodes = node.childNodes;
		if (childNodes || childNodes.length > 0) {
			for ( var i = 0; i < childNodes.length; i++) {
				if (childNodes[i].getUI().checkbox.checked)
					return true;
			}
		}
		return false;
	},

	/**
	 * 是否为半选
	 */
	halfchoose : function(node) {
		var childNodes = node.childNodes;
		if (childNodes || childNodes.length > 0) {
			for ( var i = 0; i < childNodes.length; i++) {
				if (!(childNodes[i].getUI().checkbox.checked))
					return true;
			}
		}
		return false;
	},

	createResourceViewPanel : function() {
		var options = {
			title : "资源信息",
			iconCls : "p-panel",
			region : "east",
			contentEl : 'the-resource-info',
			autoScroll : true,
			margins : '2 2 2 0',
			width : '35%',
			split : true,
			border : true
		};
		return new K.Ext.Panel(options);
	},

	/** ------ ------ ------ ------ 事件 ------ ------ ------ ------ */
	/**
	 * 设置新增或删除的资源
	 */
	setAddOrDelRs : function(node, checked) {
		var me = this;
		if (node.attributes['isRelated']) {
			if (!checked) {
				var index = $.inArray(node, me.delRoleRs);
				if (index == -1) {
					me.delRoleRs.push(node);
				}
			} else {
				var index = $.inArray(node, me.delRoleRs);
				if (index != -1) {
					me.delRoleRs.splice(index, 1);
				}
			}
		} else {
			if (checked) {
				var index = $.inArray(node, me.addRoleRs);
				if (index == -1) {
					me.addRoleRs.push(node);
				}
			} else {
				var index = $.inArray(node, me.addRoleRs);
				if (index != -1) {
					me.addRoleRs.splice(index, 1);
				}
			}
		}
	},

	/** ------ ------ ------ ------ 事件/监听 ------ ------ ------ ------ */

	/**
	 * 加载资源数据成功
	 */
	onGetRsByIdSuccesss : function(output) {
		K.autofill({
			data : output.getParameter("resource"),
			target : $("#the-resource-info")[0]
		});
	},

	/**
	 * 根据角色id查询拥有资源成功
	 */
	onGetRsByRoleIdSuccessEvent : function(output) {
		var me = this;
		var roleRs = output.getParameter("resources");
		var rsRootId = output.getParameter("roleResRoot");

		if (roleRs) {
			var value = K.trim(roleRs);
			if (value.length == 0) {
				return;
			}
			this.roleRs = roleRs.split(",");
		} else {
			this.roleRs = [];
		}

		this.addRoleRs = [];
		this.delRoleRs = [];

		this.rsTreePanel.setRootNode(this.createResourceRootNode(rsRootId));
		this.rsTreePanel.getRootNode().select();

	},

	/**
	 * 设置角色与资源关联成功后
	 */
	onAssignResourcesSuccessEvent : function() {

		$.each(this.addRoleRs, function(i, v) {
			v.attributes.isRelated = true;
		})
		$.each(this.delRoleRs, function(i, v) {
			v.attributes.isRelated = false;
		})

		this.addRoleRs = [];
		this.delRoleRs = [];

		K.msg("设置成功", this.rsTreePanel.tbar);
	},
	
	/**
	 * 设置资源树面板上功能的按钮的可用状态
	 */
	setButtonEnable : function(op) {
		if(op == 'show'){
			Ext.getCmp("saveInfoBtn").enable();
			Ext.getCmp("expandTreeBtn").enable();
		}else{
			Ext.getCmp("saveInfoBtn").disable();
			Ext.getCmp("expandTreeBtn").disable();
		}
	}
})
